package com.zgf.dao.impl;

import com.zgf.dao.AccountDao;
import com.zgf.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;
import java.util.List;

public class AccountDaoImpl implements AccountDao {


    private JdbcTemplate jt;

    public JdbcTemplate getJt() {
        return jt;
    }

    public void setJt(JdbcTemplate jt) {
        this.jt = jt;
    }

    @Override
    public Account findById(int id) {
        List<Account> account = jt.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class),id);
         return account.isEmpty()? null:account.get(0);

    }

    @Override
    public Account findByName(String name) {
        List<Account> account = jt.query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class),name);
        if (account.isEmpty()){
            return null;
        }if (account.size()>1){
            throw new RuntimeException("结果集不唯一");
        }
        return account.get(0);
    }

    @Override
    public void update(int id) {
        jt.update("UPDATE account SET name=?,money=? where id = ?", new BeanPropertyRowMapper<Account>(Account.class), "迪迦奥特曼", 10000,id);
    }

    @Override
    public void listAccount() {
        List<Account> account = jt.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
        for (Account ac : account) {
            System.out.println(ac);
        }
    }
}
